//
//  JimDelightHashTable3.cpp
//  CollectionTest
//
//  Created by Dusan Vujosevic on 2013-10-27.
//  Copyright (c) 2013 Suavetech. All rights reserved.
//

#include "JimDelightHashTable3.h"
#include <math.h>
#include <stdlib.h>

static const size_t defaultElemCount = 5;

JimDelightHashTable3::JimDelightHashTable3(size_t elementCountHint):
	CollectionBase(elementCountHint), _tableSize(elementCountHint)
{
	_table = new STBucket3<elemType>[_tableSize];
	size_t bitsNeeded = (size_t)log2f(elementCountHint);
	_mask = ~(~0 << bitsNeeded);
}

JimDelightHashTable3::~JimDelightHashTable3()
{
	delete[] _table;
}

void JimDelightHashTable3::reset()
{
	delete[] _table;
	_table = new STBucket3<elemType>[_tableSize];
}

void JimDelightHashTable3::loadElements(const void* randBytes, size_t elemCount)
{
	elemType* randElem = (elemType*)randBytes;
	for(size_t u = 0; u < elemCount; u++)
	{
		elemType elem = *randElem++;
		size_t hashVal = hash(elem);
		_table[hashVal].AddElem(elem);
	}
}

bool JimDelightHashTable3::findElement(elemType elem)
{
	size_t hashVal = hash(elem);
	return _table[hashVal].ContainsElem(elem);
}

template <typename Tkey>
void STBucket3<Tkey>::AddElem(Tkey& elem)
{
	if(_elems == NULL)
	{
		_elemsAlloc = defaultElemCount;
		_elems = (Tkey*)malloc(sizeof(Tkey) * _elemsAlloc);
	}
	else if(_elemsCount >= _elemsAlloc)
	{
		_elemsAlloc += defaultElemCount;
		_elems = (Tkey*)realloc(_elems, sizeof(Tkey) * _elemsAlloc);
	}
	// We gots enough room, park the new element
	_elems[_elemsCount] = elem;
	_elemsCount++;
}

template <typename Tkey>
bool STBucket3<Tkey>::ContainsElem(const Tkey& elem) const
{
	for(size_t u = 0; u < _elemsCount; u++)
	{
		if(_elems[u] == elem)
			return true; // already gots it, return
	}
	return false;
}
